// @flow
import React, { Component } from 'react'
import { Form, Modal, Input, Select, message } from 'antd'
import R from 'ramda'
import { getSpecs } from 'utils/GeneralOptions'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const FormItem = Form.Item
const Option = Select.Option
type Props = {
  form: Object,
  visible: boolean,
  closeModal: Function,
  parentId: string,
  deviceSorts: Array<Object>,
  refreshView: Function
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

type States = {
  confirmLoading: boolean,
  parentId: string,
  pointData: Array<any>,
  modalDeviceType: Array<Object>,
  modalDeviceSpecs: Array<any>
}
class DevicePartModal extends Component {
  props: Props
  state: States
  handleSubmitComponent: Function
  handleOk: Function
  getPointData: Function
  changeType: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      confirmLoading: false,
      pointData: [],
      parentId: '',
      modalDeviceType: [],
      modalDeviceSpecs: []
    }
    this.handleSubmitComponent = this.handleSubmitComponent.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.getPointData = this.getPointData.bind(this)
    this.changeType = this.changeType.bind(this)
  }

  handleSubmitComponent () {}

  componentWillReceiveProps (nextProps: Props) {
    if (!R.equals(nextProps, this.props)) {
      const { deviceSorts } = nextProps
      this.setState({
        modalDeviceType: deviceSorts.map((d, i) => {
          return <Option key={d.id} value={d.value}>{d.label}</Option>
        })
      })
    }
  }
  componentDidMount () {
    this.getPointData()
  }

  changeType (value) {
    getSpecs(value, (json) => {
      this.setState({
        modalDeviceSpecs: json.result.map((d, i) => {
          return <Option key={d.value + i} value={d.value}>{d.label}</Option>
        })
      })
    })
  }
  handleOk () {
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        confirmLoading: true
      })
      const { closeModal, refreshView } = this.props
      const values = {
        ...fieldsValue,
        parentId: this.props.parentId
      }
      universalFetch(`${__SERVICE_API__}device/templates/devices`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(values)
      })
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('添加成功')
        this.setState({
          confirmLoading: false
        })
        refreshView(1, 20)
        closeModal()
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        message.error('添加失败')
        this.setState({
          confirmLoading: false
        })
      })
    })
  }

  getPointData () {
    universalFetch(`${__SERVICE_API__}device/templates/monitors/points`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        pointData: json.result
      })
      // pointData = json.result
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { closeModal, visible } = this.props
    const { confirmLoading, pointData } = this.state
    const pointChildren = pointData.map((d, i) => {
      return <Option key={i} value={d.id}>{d.sensorName}</Option>
    })
    return (
      <Modal
        title='添加部件'
        visible={visible}
        onCancel={closeModal}
        onOk={this.handleOk}
        confirmLoading={confirmLoading}
        >
        <Form onSubmit={this.handleSubmitComponent}>
          <FormItem {...formItemLayout} label='名称' hasFeedback>
            {getFieldDecorator('name', {
              rules: [
                { required: true, message: '请输入名称', whitespace: true }
              ]
            })(
              <Input placeholder='请输入名称' ref={(e) => {
                document.querySelector('#name').focus()
              }} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='类型'>
            {getFieldDecorator('type', {
            })(
              <Input placeholder='请选择类型' />
              // <Select showSearch
              //   filterOption={(input, option) => {
              //     return option.props.children.indexOf(input) >= 0
              //   }} style={{ width: 280 }}
              //   placeholder='请选择类型'
              //   onChange={this.changeType}>
              //   {this.state.modalDeviceType}
              // </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='型号'>
            {getFieldDecorator('spec', {})(
              <Input placeholder='请选择型号' />
              // <Select showSearch
              //   filterOption={(input, option) => {
              //     return option.props.children.indexOf(input) >= 0
              //   }} style={{ width: 280 }}
              //   placeholder='请选择型号'
              //   >
              //   {this.state.modalDeviceSpecs}
              // </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='测点' hasFeedback>
            {getFieldDecorator('monitorPointIds', {})(
              <Select showSearch mode='multiple'
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择测点'
                >
                {pointChildren}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='备注'>
            {getFieldDecorator('remark', {})(
              <Input placeholder='备注信息' style={{ width: 300 }} type='textarea' autosize />
            )}
          </FormItem>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(DevicePartModal)
